package com.makingTeam.config.aop;


import com.makingTeam.comment.annotation.DB;
import com.makingTeam.config.dataSource.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class DbAspect {


    @Pointcut("@annotation(com.makingTeam.comment.annotation.DB)")
    public void dynamicDataSource(){}


    @Around(value = "dynamicDataSource()")
    public Object datasourceAroud(ProceedingJoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        if (method.isAnnotationPresent(DB.class)){
            DB dbAnnotation = method.getAnnotation(DB.class);
            DataSourceContextHolder.setDataSourceType(dbAnnotation.value());
        }
        try{
            return point.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            DataSourceContextHolder.clearDataSourceType();
        }
    }
}
